<template>
  <div class="currencyItem">
    <!-- 左侧币种信息 -->
    <div class="left">
      <image-load :filePath="currencyItem.logo" class="leftImg" v-if="showLeftImg" />
      <div>
        <div class="topText ff-num">
          <div class="textTop fw-num">
            <div class="symbol-top">{{ symbolParts[0] }}</div>
            <div class="symbol-bottom">{{ symbolParts[1] }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 动态折线图 -->
    <div class="chart-container">
      <svg 
        class="line-chart" 
        viewBox="0 0 100 40"
        preserveAspectRatio="none"
      >
        <path 
          :d="pathData"
          :stroke="lineColor"
          fill="none"
          stroke-width="1"
          stroke-linecap="round"
        />
      </svg>
    </div>

    <!-- 右侧价格列 -->
    <div class="right-column">
      <div class="price fw-num">
        {{ animatedPrice }}
      </div>
      <div 
        :class="[
          _isRFD(
            tradeStore.allCoinPriceInfo[currencyItem.coin]?.openPrice,
            tradeStore.allCoinPriceInfo[currencyItem.coin]?.close
          ),
          'change-rate rfd-sign fw-num'
        ]"
      >
        {{ tradeStore.allCoinPriceInfo[currencyItem.coin]?.priceChangePercent }}%
      </div>
    </div>
  </div>
</template>

<script setup>
import { useTradeStore } from '@/store/trade/index'
import { priceFormat } from '@/utils/decimal.js'
import { ref, watch, onMounted, onUnmounted, computed } from 'vue'

const tradeStore = useTradeStore()

const props = defineProps({
  currencyItem: {
    type: Object,
    default: {}
  },
  showLeftImg: {
    type: Boolean,
    default: true
  }
})

// 价格动画相关
const animatedPrice = ref('')
let animationFrame = null
const animationDuration = 800

const currentPrice = computed(() => {
  return parseFloat(tradeStore.allCoinPriceInfo[props.currencyItem.coin]?.close || 0)
})

watch(currentPrice, (newVal, oldVal) => {
  const startVal = parseFloat(oldVal || 0)
  const endVal = parseFloat(newVal || 0)
  const startTime = Date.now()

  if (animationFrame) {
    cancelAnimationFrame(animationFrame)
  }

  const animate = () => {
    const progress = Math.min((Date.now() - startTime) / animationDuration, 1)
    const currentVal = startVal + (endVal - startVal) * progress
    animatedPrice.value = priceFormat(currentVal)

    if (progress < 1) {
      animationFrame = requestAnimationFrame(animate)
    } else {
      animatedPrice.value = priceFormat(endVal)
    }
  }

  animatedPrice.value = priceFormat(startVal)
  animationFrame = requestAnimationFrame(animate)
}, { immediate: true })

// 折线图相关
const pathData = ref('')

const generatePath = () => {
  try {
    const points = []
    const segments = 6
    const baseY = 20
    
    for(let i = 0; i <= segments; i++) {
      const x = (i * 100) / segments
      const y = baseY + (Math.random() * 36 - 18)
      points.push({x, y})
    }

    let path = `M ${points[0].x} ${points[0].y} `
    points.forEach((point, index) => {
      if(index > 0) {
        const prev = points[index - 1]
        const cp1x = prev.x + (point.x - prev.x) * 0.2
        const cp1y = prev.y + (Math.random() * 15 - 7.5)
        const cp2x = prev.x + (point.x - prev.x) * 0.8
        const cp2y = point.y + (Math.random() * 15 - 7.5)
        path += `C ${cp1x} ${cp1y}, ${cp2x} ${cp2y}, ${point.x} ${point.y} `
      }
    })
    return path
  } catch {
    return "M 0 20 C 20 15, 30 25, 50 20 S 80 15, 100 20"
  }
}

let pathTimer = null
onMounted(() => {
  pathData.value = generatePath()
  
  pathTimer = setInterval(() => {
    pathData.value = generatePath()
  }, 3000)
})

onUnmounted(() => {
  clearInterval(pathTimer)
  if (animationFrame) {
    cancelAnimationFrame(animationFrame)
  }
})

// 颜色计算（修复版本）
const lineColor = computed(() => {
  // tradeStore.allCoinPriceInfo[currencyItem.coin]?.close
  const coinInfo = tradeStore.allCoinPriceInfo[props.currencyItem.coin] || {}
  
  const changePercent = (Number(coinInfo?.close) - Number(coinInfo?.openPrice)) || 0  
  if (changePercent < 0) return '#FF4444'
  if (changePercent > 0) return '#00C853'
  return '#888888'
})

// 拆分币对
const symbolParts = computed(() => {
  if (!props.currencyItem.showSymbol) return ['', '']
  const arr = props.currencyItem.showSymbol.split('/')
  return [arr[0] || '', arr[1] || '']
})
</script>

<style lang="scss" scoped>
.currencyItem {
  padding: 12px 15px;
  display: flex;
  align-items: center; 
  border-radius: 8px;
  margin-bottom: 8px;

  .left {
    display: flex;
    align-items: center;
    
    .leftImg {
      width: 28px;
      height: 28px;
      margin-right: 12px;
      border-radius: 50%;
    }

    .textTop {
      font-size: 14px;
      color: var(--ex-font-color6);
      line-height: 1.4;
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      .symbol-top {
        font-size: 14px;
        font-weight: bold;
        color: #000;
        line-height: 1.2;
      }
      .symbol-bottom {
        font-size: 12px;
        color: #999;
        line-height: 1.2;
        font-weight: 400;
      }
    }
  }

  .chart-container {
    padding: 0 50px;
    // flex: 1;
    // height: 50px;
    overflow: visible;
    
    .line-chart {
      width: 100%;
      height: 100%;
      
      path {
        transition: 
          d 0.8s cubic-bezier(0.4, 0, 0.2, 1),
          stroke 0.3s ease; /* 添加颜色过渡 */
        filter: 
          drop-shadow(0 1px 2px rgba(0,0,0,0.3))
      }
    }
  }

  .right-column {
    width: 100px;
    text-align: right;
    padding-left: 0;

    .price {
      font-size: 14px;
      color: var(--ex-default-font-color);
      font-weight: 500;
      font-variant-numeric: tabular-nums;
      transition: opacity 0.3s ease;
    }

    .change-rate {
      font-size: 13px;
      border-radius: 4px;
      display: inline-block;
      min-width: 70px;
    }
  }
}
</style>